package ibm.websphere.monitor.action;

import java.io.File;

import ibm.websphere.monitor.bean.UserInfo;
import ibm.websphere.monitor.common.SpringContext;
import ibm.websphere.monitor.service.IMenuService;
import ibm.websphere.monitor.service.IThreadService;
import ibm.websphere.monitor.service.IUserService;
import ibm.websphere.monitor.util.Constants;
import ibm.websphere.monitor.util.RandomSvg;
import ibm.websphere.monitor.util.UtilTool;
import org.apache.log4j.Logger;


/**
 * <pre>
 *	@Description 登录处理ACTION
 * </pre>
 * @copyright www.timotai.net
 * @author 这家伙真懒
 * @date 2016-1-12
 **/

public class LoginManagerAction extends BaseAction {


    private static final long serialVersionUID = -6198675064165542564L;

    /**调试日志**/
    private Logger logger = Logger.getLogger(LoginManagerAction.class);

    /**初始化IUserService对象**/
    private IUserService userService = SpringContext.getBean(IUserService.class);

    /**初始化IMenuService对象**/
    private IMenuService menuService = SpringContext.getBean(IMenuService.class);

    /**用户信息**/
    private UserInfo user;

    /**随机码**/
    private String randomCode;

    /**用户名**/
    private String userName;

    /**密码**/
    private String passWord;

    /**登陆出错码**/
    private String errorCode="";

    /**用户输入的验证码**/
    private String rand;

    /**树菜单**/
    private String treeMenu;

    /**判断是退出还是生成验证码**/
    private String type="";


    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getTreeMenu() {
        return treeMenu;
    }

    public void setTreeMenu(String treeMenu) {
        this.treeMenu = treeMenu;
    }

    public String getRand() {
        return rand;
    }

    public void setRand(String rand) {
        this.rand = rand;
    }

    public String getPassWord() {
        return passWord;
    }

    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getRandomCode() {
        return randomCode;
    }

    public void setRandomCode(String randomCode) {
        this.randomCode = randomCode;
    }

    public UserInfo getUser() {
        return user;
    }

    public void setUser(UserInfo user) {
        this.user = user;
    }

    public String getErrorCode() {
        return errorCode;
    }

    public void setErrorCode(String errorCode) {
        this.errorCode = errorCode;
    }


    /**
     * <pre>
     * 	生成验证码
     * </pre>
     * @return
     */
    public String getRandom() {
        try {

            logger.info("【用户登陆】【验证码生成】【开始生成验证码】");

            // 生成四位随机验证码(下面确定随机循环的范围)
            String randStr = "0123456789";
            StringBuffer generateRandStr = new StringBuffer();
            java.util.Random rand = new java.util.Random();

            // 你想生成的随机数的长度
            int randStrLength = 4;

            for (int i = 0; i < randStrLength; i++) {
                int randNum = rand.nextInt(randStr.length());
                generateRandStr.append(randStr.substring(randNum, randNum + 1));
            }

            String path = "/page/pictures/";
            String realPath = request.getRealPath(path);

            RandomSvg hw = new RandomSvg();

            // 删除验证码图片目录中的所有图片文件
            File picPath = new File(realPath);

            hw.deletePath(picPath);
            // 生成验证码图片
            hw.getRandomCode(generateRandStr.toString(), realPath+"/" + generateRandStr.toString() + ".jpg");
            randomCode = generateRandStr.toString();

            logger.info("【用户登陆】【验证码生成】【验证码："+randomCode+"】");
            logger.info("【用户登陆】【验证码生成】【验证码生成路径："+ realPath+"/" + generateRandStr.toString() + ".jpg"+"】");
        }
        catch (Exception ex) {
            ex.getMessage();
            ex.printStackTrace();
            logger.error("【用户登陆】【验证码生成】【验证码生成异常】"+ex.getMessage());
        }

        if(type.equals("exit")){
            UserInfo user = (UserInfo)this.getLoginUser();
            //非法用户进入或登录超时
            if(user == null){
                errorCode = "4"; //请输入用户名。;
                return ERROR;
            }
        }
        request.getSession().invalidate();

        request.getSession().removeAttribute(Constants.SESSION_USER);


        this.setTarget(Constants.WAS_PAGES_ROOT + "login.jsp");

        return Constants.DEFAULT_VIEW;
    }

    /**
     * <pre>
     * 	鉴权用户登陆信息
     * </pre>
     * @return
     */
    public String login(){
        try{

            //验证登录用户名和密码是否正确
            user = userService.finaUserByUserName(userName);

            if(user == null){
                //记录登录用户名验证失败
                logger.info("【登录验证】 【输入的用户名： "+userName+"】 【操作员不存在】");
                errorCode = "0"; //该用户不存在，请确认后重试。;
                return ERROR;
            }

            //验证操作员输入密码是否合法
            if(!passWord.equals(user.getPassword())){
                //记录登录密码验证失败
                logger.info("【登录验证】 【输入的用户名： "+userName+"】 【输入密码错误】");
                errorCode = "1";//密码错误，请确认后重试。;
                return ERROR;
            }

            //判断该客户是否处于激活状态
            if(user.getIsActive() != 0){
                //记录登录密码验证失败
                logger.info("【登录验证】 【输入的用户名： "+userName+"】 【操作员没有被激活】");
                errorCode = "2";//该用户没有被激活，请联系管理员后重试。;
                return ERROR;
            }

//            //验证验证码是否正确
//            if(!rand.equals(randomCode)){
//                //记录验证码验证失败日志
//                logger.info("【登录验证】 【输入的用户名： " + userName + "】 【验证验证码】");
//                errorCode = "3";//验证码错误，请重新输入;
//                return ERROR;
//            }
        }catch(Exception e){
            e.printStackTrace();
            logger.error("【登录验证】【登陆时发生异常："+e.getMessage()+"】");        }

        /**IP地址**/
        user.setIp(request.getRemoteHost());

        String contextPath=request.getContextPath();
        try{
//            System.out.println(menuService.findFatherMenu(0L));
            treeMenu = UtilTool.dump(menuService.findFatherMenu(0L),menuService.findMenu(), contextPath);
            System.out.println(treeMenu);
        }catch(Exception ex){
            ex.printStackTrace();
            System.out.println(ex.getMessage());
        }
        logger.info(user.getUserName()+"【登陆验证】【生成菜单树："+treeMenu+"】");

        request.getSession().setAttribute("treeMenu", treeMenu);

        //
        //user.getTranslate();
        //
        //user.getRoleId().getTranslate();
        /**把USER对象存放在SESSION中**/
        request.getSession().setAttribute(Constants.SESSION_USER, user);


        return SUCCESS;
    }
}